package com.zheng.hospital.controller;

import com.zheng.hospital.common.result.CommonResult;
import com.zheng.hospital.service.SmsService;
import com.zheng.hospital.utils.RandomCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/sms")
public class SmsApiController {
    @Autowired
    SmsService smsService;
    @Autowired
    RedisTemplate<String, String> redisTemplate;

    /**
     * 发送手机验证码
     * @param phone
     */
    public CommonResult sendCode(@PathVariable String phone) {
        //从redis获取验证码，如果获取获取到，返回ok
        // key 手机号  value 验证码
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) {
            return CommonResult.ok();
        }
        //如果从redis获取不到则生成验证码
        code = RandomCodeUtil.getSixBitRandom();
        //调用service方法发送短信
        boolean isSuccess = smsService.send(phone, code);
        if (isSuccess) {
            //验证码存入redis，保存时间为两分钟
            redisTemplate.opsForValue().set(phone, code, 2, TimeUnit.MINUTES);
            return CommonResult.ok();
        } else {
            return CommonResult.fail().message("发送短信失败");
        }
    }
    }
